package com.jnzc.ocr.serv.third.api.impl;

import com.jnzc.ocr.serv.third.api.QiniuUploadApi;
import com.jnzc.ocr.serv.third.prop.QiniuProp;
import com.jnzc.ocr.serv.third.result.QiniuUpdateConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class QiniuUploadApiImpl implements QiniuUploadApi {

    private static final Logger logger = LoggerFactory.getLogger(QiniuUploadApiImpl.class);

    @Autowired
    private QiniuProp qiniuProp;

    @Override
    public QiniuUpdateConfig getConfig() {
        QiniuUpdateConfig result = new QiniuUpdateConfig();
        Auth auth = Auth.create(qiniuProp.getAccessKey(), qiniuProp.getSecretKey());
        String token = auth.uploadToken(qiniuProp.getBucket());
        result.setToken(token);
        result.setUploadDomain(qiniuProp.getUploadDomain());
        result.setUploadMaxSize(qiniuProp.getUploadMaxSize());
        return result;
    }

    @Override
    public void delete(String url) {
        if(StringUtils.isEmpty(url)){
            return;
        }
        String key = url.substring(url.lastIndexOf("/") + 1);
        Auth auth = Auth.create(qiniuProp.getAccessKey(), qiniuProp.getSecretKey());
        Configuration cfg = new Configuration(Zone.autoZone());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            Response response = bucketManager.delete(qiniuProp.getBucket(), key);
            logger.info("response.body: {}", response.bodyString());
        } catch (QiniuException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
